import React, { useState, useEffect, memo } from 'react';
import styles from './index.module.less';
import ContractSelectModal from '@/components/ContractSelectModal';
import { Picker, List } from 'antd-mobile-v2';
import { FormListItem } from '@/components/form-group/interface';
import classnames from 'classnames';

export interface Props extends FormListItem {
  value?: any;
  onChange?: (params: any) => void;
  setValues?: (params: any) => void;
}

const TreeSelecter: React.FC<Props> = (props) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [receiveData, setReceiveData] = useState<any[]>([]);

  useEffect(() => {
    // console.log(`receiveData ${props.valueKey} `, props.cellProps.receiveData);
    const data = props.cellProps.receiveData;
    if (!data?.[0]?.id) return;
    // console.log(`tree data ${props.valueKey}`, data);
    setReceiveData(
      data?.map((item: { id: string; name: string; userOrgType: number }) => ({
        text: item.name,
        type: item.userOrgType,
        value: item.id
      }))
    );
    // props.onChange(data);
    console.log('setValues', data);
    props.setValues({ [props.valueKey]: data });
  }, [props.cellProps.receiveData]);

  const openModal = () => {
    setVisible(true);
  };

  const closeModal = () => {
    setVisible(false);
  };

  const onSelect = (isHandle: boolean, v: any[]) => {
    const value = v;
    props.setValues({ [props.valueKey]: value });
    props.cellProps.onChange && props.cellProps.onChange(value);
    isHandle && props.onChange(value);
    setVisible(false);
  };

  const formatData = () => {
    const { value } = props;
    let formatValue = [];
    if (value?.length) {
      formatValue = value.map((item: any) => {
        return item.title || item.name;
      });
    }
    return formatValue?.join('，');
  };
  // console.log('receiveData', props.valueKey, receiveData);
  return (
    <>
      <Picker
        {...props}
        key={props.valueKey}
        disabled
        cols={1}
        {...props.cellProps}
        format={formatData}
      >
        <List.Item
          className={classnames(
            styles['picker-item'],
            'ignore-ratio-border-bottom-left-15',
            props.value?.length ? styles['active'] : styles['holder']
          )}
          arrow='horizontal'
          onClick={openModal}
        >
          {props.label}
        </List.Item>
      </Picker>
      <ContractSelectModal
        modalStatus={visible}
        closeModal={closeModal}
        submit={(isHandle: boolean, v: any[]) => onSelect(isHandle, v)}
        receiveData={receiveData} // 表单回填的数据，使用时参考公文录入功能的表单回填写法
        type={props.cellProps.type} // 类型 'dept' | 'person' | 'all'
        mode={props.cellProps.mode} // 单选多选模式 'single' | 'multiple'
        orgData={props.cellProps.orgData} // 树形数据源
        height={props.cellProps.height} // 虚拟列表高度
      />
    </>
  );
};

export default memo(TreeSelecter);
